package com.scs.application.modules.msg.provider;

import com.scs.application.core.msg.domain.RawMessage;
import com.scs.application.core.msg.domain.SceneMessage;
import com.scs.application.core.msg.domain.SceneMessageParam;
import com.scs.application.core.msg.enums.MessageType;
import com.scs.application.core.utils.FreeMarkers;
import com.scs.application.core.utils.StringUtils;
import com.scs.application.modules.msg.entity.Template;
import com.scs.application.modules.upms.vo.UserVO;
import com.google.common.collect.Maps;

import java.util.List;
import java.util.Map;

public interface BuildMessageProvider<T extends RawMessage> {

    /**
     * 创建消息
     *
     * @param userInfoVOList
     * @param template
     * @param msg
     * @return
     */
    List<RawMessage> messagesBuild(List<UserVO> userInfoVOList, Template template, SceneMessage msg);


    default boolean support(Class<? extends RawMessage> clz) {
        return false;
    }

    /**
     * 获取参数
     *
     * @param msg
     * @return
     */
    default Map<String, Object> getSuitableParams(SceneMessage msg, MessageType messageType) {
        List<SceneMessageParam> params = msg.getParams();
        if (params == null) {
            return Maps.newHashMap();
        }
        Map<String, Object> map = Maps.newHashMap();
        for (SceneMessageParam param : params) {
            if (param.getSuitableMessageTypes().contains(messageType)) {
                map.put(param.getName(), param.getValue());
            }
        }
        return map;
    }


    /**
     * 获取消息内容
     *
     * @param template    模板
     * @param msg
     * @param messageType
     * @return
     */
    default String getContent(Template template, SceneMessage msg, MessageType messageType) {
        String content = null;
        try {
            // ueditor 富文本
            content = StringUtils.defaultString(template.getContent())
                    .replaceAll("《", "<")
                    .replaceAll("》", ">")
                    .replaceAll("&quot;", "\"")
                    .replaceAll("&#39;", "'");

            content = FreeMarkers.renderString(content, getSuitableParams(msg, messageType));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return content;
    }

}
